package com.che.software.testato.business;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.che.software.testato.business.exception.MatrixResultCreationManagerException;
import com.che.software.testato.business.exception.MatrixResultSearchManagerException;
import com.che.software.testato.domain.dao.IIterationDAO;
import com.che.software.testato.domain.dao.IMatrixItemDAO;
import com.che.software.testato.domain.dao.IMatrixResultDAO;
import com.che.software.testato.domain.dao.jdbc.exception.MatrixResultCreationDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.MatrixResultSearchDAOException;
import com.che.software.testato.domain.entity.Iteration;
import com.che.software.testato.domain.entity.MatrixItem;
import com.che.software.testato.domain.entity.MatrixResult;
import com.che.software.testato.domain.entity.search.IterationSearch;
import com.che.software.testato.domain.entity.search.MatrixItemSearch;
import com.che.software.testato.domain.entity.search.MatrixResultSearch;

/**
 * Manager dedicated to the matrix results.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @since August, 2011.
 * 
 *        This file is part of Testato.
 * 
 *        Testato is free software: you can redistribute it and/or modify it
 *        under the terms of the GNU General Public License as published by the
 *        Free Software Foundation, either version 3 of the License, or (at your
 *        option) any later version.
 * 
 *        Testato is distributed in the hope that it will be useful, but WITHOUT
 *        ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *        FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 *        for more details.
 * 
 *        You should have received a copy of the GNU General Public License
 *        along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 *        Testato's logo is a creation of Arrioch
 *        (http://arrioch.deviantart.com/) and it's distributed under the terms
 *        of the Creative Commons License.
 */
@Service("matrixResultManager")
public class MatrixResultManager {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(MatrixResultManager.class);

	/**
	 * Members.
	 */
	@Autowired
	private IIterationDAO iterationDAO;
	@Autowired
	private IMatrixItemDAO matrixItemDAO;
	@Autowired
	private IMatrixResultDAO matrixResultDAO;

	/**
	 * Calculates and inserts the consistency index of a given iteration
	 * assignment.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationId the given iteration assignment id.
	 * @since August, 2011.
	 * @throws MatrixResultCreationManagerException if an error occurs during
	 *         the creation.
	 */
	public void createConsistencyIndex(int iterationId) throws MatrixResultCreationManagerException {
		LOGGER.debug("createConsistencyIndex(" + iterationId + ").");
		Map<Integer, Double> vector = new HashMap<Integer, Double>();
		try {
			List<MatrixResult> results = matrixResultDAO.searchMatrixResult(new MatrixResultSearch(iterationId));
			for (MatrixResult result : results) {
				MatrixItemSearch searchBean = new MatrixItemSearch(iterationId);
				searchBean.setFirstScript(result.getScriptId());
				List<MatrixItem> items = matrixItemDAO.searchMatrixItem(searchBean);
				double vectorValue = 0;
				for (int i = 0; i < items.size(); i++) {
					vectorValue += (items.get(i).getValue() * results.get(i).getPercentage());
				}
				vector.put(result.getScriptId(), vectorValue);
			}
			double total = 0;
			for (MatrixResult result : results) {
				total += vector.get(result.getScriptId()) / result.getPercentage();
			}
			IterationSearch searchBean = new IterationSearch();
			searchBean.setIterationAssignmentId(iterationId);
			Iteration iteration = iterationDAO.searchIteration(searchBean).get(0);
			iteration.setConsistencyIndex((results.size() == 1) ? 0 : ((total / results.size()) - results.size()) / (results.size() - 1));
			iterationDAO.updateIteration(iteration);
		} catch (Exception e) {
			throw new MatrixResultCreationManagerException(e);
		}
	}

	/**
	 * Creates the matrix results for a given iteration assignment. The related
	 * matrix must be completed before calling this method.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationId the given iteration id.
	 * @since August, 2011.
	 * @throws MatrixResultCreationManagerException if an error occurs during
	 *         the creation.
	 */
	public void createMatrixResults(int iterationId) throws MatrixResultCreationManagerException {
		LOGGER.debug("createMatrixResults(" + iterationId + ").");
		try {
			matrixResultDAO.createMatrixResults(iterationId);
		} catch (MatrixResultCreationDAOException e) {
			throw new MatrixResultCreationManagerException(e);
		}
	}

	/**
	 * Matrix result search from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the criterions to use for the search.
	 * @return the resulting object list.
	 * @since August, 2011.
	 * @throws MatrixResultSearchManagerException if an error occurs during the
	 *         search.
	 */
	public List<MatrixResult> searchMatrixResult(MatrixResultSearch searchBean) throws MatrixResultSearchManagerException {
		LOGGER.debug("searchMatrixResult().");
		try {
			return matrixResultDAO.searchMatrixResult(searchBean);
		} catch (MatrixResultSearchDAOException e) {
			throw new MatrixResultSearchManagerException(e);
		}
	}

	/**
	 * Getter for the private field value matrixResultDAO.
	 * 
	 * @return the matrixResultDAO field value.
	 */
	public IMatrixResultDAO getMatrixResultDAO() {
		return matrixResultDAO;
	}

	/**
	 * Setting a value to the matrixResultDAO field.
	 * 
	 * @param matrixResultDAO the value to set.
	 */
	public void setMatrixResultDAO(IMatrixResultDAO matrixResultDAO) {
		this.matrixResultDAO = matrixResultDAO;
	}

	/**
	 * Getter for the private field value matrixItemDAO.
	 * 
	 * @return the matrixItemDAO field value.
	 */
	public IMatrixItemDAO getMatrixItemDAO() {
		return matrixItemDAO;
	}

	/**
	 * Setting a value to the matrixItemDAO field.
	 * 
	 * @param matrixItemDAO the value to set.
	 */
	public void setMatrixItemDAO(IMatrixItemDAO matrixItemDAO) {
		this.matrixItemDAO = matrixItemDAO;
	}

	/**
	 * Getter for the private field value iterationDAO.
	 * 
	 * @return the iterationDAO field value.
	 */
	public IIterationDAO getIterationDAO() {
		return iterationDAO;
	}

	/**
	 * Setting a value to the iterationDAO field.
	 * 
	 * @param iterationDAO the value to set.
	 */
	public void setIterationDAO(IIterationDAO iterationDAO) {
		this.iterationDAO = iterationDAO;
	}
}